<template>
  <div>
    <div>
      <el-button class="add-rule" @click="handleClickAddRule">{{$t('zhongqi.setting.addRule')}}</el-button>

      <div class="rule-list" v-for="(item, index) in ruleList" :key="index">
        <div class="rule-list-con">
          <div class="rule-item">
            <span>{{$t('zhongqi.setting.ruleName')}}：{{ item.ruleName }}</span>
          </div>
          <div class="rule-item">
            <span>{{$t('zhongqi.setting.warrantyStatus')}}：{{ warrantyStatus[item.attribute.qualityStatus] }}</span>
          </div>
          <div class="rule-item">
            <span>{{$t('zhongqi.setting.chargeOrNot')}}：{{ freeOfCharge[item.attribute.isFree] }}</span>
          </div>
        </div>
        <button type="button" class="btn-text form-select-setting-delete" @click="handleClickDeleteRule(index)"><i class="iconfont icon-minus-fill"></i></button>
      </div>
    </div>

    <!-- 新增规则弹框 -->
    <base-modal class="service-dialog-container" :title="title" :show.sync="visible" width="500px">
      <el-form ref="formRef" :model="form" :rules="rules">
        <el-form-item :label="$t('common.base.rulerName')" prop="ruleName">
          <el-input v-model="form.ruleName" maxlength="100" clearable></el-input>
        </el-form-item>

        <!-- 质保状态 -->
        <el-form-item :label="$t('common.form.preview.qualityField.label3')" prop="qualityStatus">
          <el-select v-model="form.qualityStatus" :placeholder="$t('task.tip.applyMaterialTip6')" :style="{ width: '100%' }" clearable>
            <el-option :label="$t('common.base.warranty')" value="IN"></el-option>
            <el-option :label="$t('common.base.surrender')" value="OUT"></el-option>
          </el-select>
        </el-form-item>

        <!-- 收费/免费 -->
        <el-form-item :label="$t('zhongqi.setting.chargeOrNot')" prop="isFree">
          <el-select v-model="form.isFree" :placeholder="$t('zhongqi.setting.text4')" :style="{ width: '100%' }" clearable>
            <el-option :label="$t('zhongqi.setting.charge')" value="charge"></el-option>
            <el-option :label="$t('zhongqi.setting.free')" value="free"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">{{ $t('common.base.close') }}</el-button>
        <el-button type="primary" @click="submit('formRef')">{{ $t('common.base.submit') }}</el-button>
      </div>
    </base-modal>
  </div>
</template>

<script>
import i18n from '@src/locales';

export default {
  name: 'settlement-rules',
  props: {
    field: {
      type: Object,
      default: () => ({}),
    },
    fields: {
      type: Array,
      default: () => [],
    },
    value: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      title: i18n.t('zhongqi.setting.addRule'),
      visible: false,
      form: {
        ruleName: '',
        qualityStatus: '',
        isFree: '',
      },
      rules: {
        ruleName: [
          { required: true, message: i18n.t('product.setting.qrCodeSet.rulers.des1'), trigger: 'blur' },
          { max: 100, message: i18n.t('zhongqi.setting.text5'), trigger: 'blur' },
        ],
        qualityStatus: [{ required: true, message: i18n.t('task.tip.applyMaterialTip6'), trigger: 'change' }],
        isFree: [{ required: true, message: i18n.t('zhongqi.setting.text4'), trigger: 'change' }],
      },
      ruleList: [],
      warrantyStatus: {
        IN: i18n.t('common.base.warranty'),
        OUT: i18n.t('common.base.surrender')
      },
      freeOfCharge: {
        charge: i18n.t('zhongqi.setting.charge'),
        free: i18n.t('zhongqi.setting.free')
      }
    };
  },
  // computed: {
  //   ruleList() {
  //     return this.field?.setting?.ruleList || []
  //   },
  // },
  mounted() {
    this.ruleList = this.field?.setting?.ruleList || []
  },
  methods: {
    /**
     * @description 打开添加规则弹窗
     */
    handleClickAddRule() {
      this.$refs['formRef'].resetFields();

      this.visible = true;
    },
    /**
     * @description 提交
     */
    submit(formName) {
      const { ruleName, qualityStatus, isFree } = this.form;

      this.$refs[formName].validate(valid => {
        if (valid) {
          // 校验是否有重复项 校验质保状态和收费免费排列组合是否重复
          let isRepeat = (this.ruleList || []).some(v => (v?.attribute.qualityStatus === qualityStatus && v?.attribute.isFree === isFree) || v.ruleName === ruleName);
          if (isRepeat) {
            return this.$message.warning(this.$t('zhongqi.setting.sameTip'));
          }
          
          // 修改服务项目 或者 物料核销的规则，如果质保状态和收费免费一致会同步更新另一个
          this.fields.forEach(item => {
            if (item.fieldName === 'serviceIterm' || item.fieldName === 'materialVerifyEliminate') {
              (item?.setting?.ruleList || []).forEach(v => {
                if (v.attribute.qualityStatus === qualityStatus && v.attribute.isFree === isFree) {
                  v.ruleName = ruleName;
                }
              })
            }
          })
          
          this.ruleList.push({
            ruleName: this.form.ruleName,
            attribute: {
              qualityStatusName: this.warrantyStatus[qualityStatus],
              isFreeName: this.freeOfCharge[isFree],
              ...this.form
            }
          });

          this.visible = false;

          
          this.$emit('saveRule', this.ruleList)

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 删除规则
    handleClickDeleteRule(index) {
      this.ruleList.splice(index, 1);
      this.$emit('saveRule', this.ruleList)
    },
  },
};
</script>

<style lang="scss" scoped>
.service-dialog-container {
  ::v-deep .base-modal-body {
    padding: 16px 24px;
  }
}
.add-rule {
  width: 100%;
  margin: 12px 0;
}
.rule-list {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  &-con {
    width: 290px;
    background: #f5f5f5;
    padding: 8px;
    border-radius: 6px;
  }
  .rule-item {
    height: 30px;
    line-height: 30px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>